package com.ums.servicezuul.route;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;

public class CustomRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {

    public final static Logger logger = LoggerFactory.getLogger(CustomRouteLocator.class);

    private ZuulProperties properties;

    public CustomRouteLocator(String servletPath, ZuulProperties properties) {
        super(servletPath, properties);
        this.properties = properties;
        logger.info("servletPath:{}", servletPath);

    }

        @Override
    public void refresh() {
        doRefresh();
    }

    @Override
    protected Map<String, ZuulProperties.ZuulRoute> locateRoutes() {
        LinkedHashMap<String, ZuulProperties.ZuulRoute> routesMap = new LinkedHashMap<>();
        //从application.properties中加载路由信息
        routesMap.putAll(super.locateRoutes());
        //从db中加载路由信息
        routesMap.putAll(locateRoutesFromDB());
        //优化一下配置
        LinkedHashMap<String, ZuulProperties.ZuulRoute> values = new LinkedHashMap<>();
        for (Map.Entry<String, ZuulProperties.ZuulRoute> entry : routesMap.entrySet()) {
            String path = entry.getKey();
            // Prepend with slash if not already present.
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            if (StringUtils.hasText(this.properties.getPrefix())) {
                path = this.properties.getPrefix() + path;
                if (!path.startsWith("/")) {
                    path = "/" + path;
                }
            }
            values.put(path, entry.getValue());
        }
        return values;
    }

    public Map<String, ZuulProperties.ZuulRoute> locateRoutesFromDB(){
        System.out.println("读取配置"+new Date());
        Map<String, ZuulProperties.ZuulRoute> stringZuulRouteMap = new LinkedHashMap<>();

        byte[] bytes = new byte[0];
        try {
            bytes = Files.readAllBytes(Paths.get("D:\\GitRepository\\springcloudtest\\service-zuul\\src\\main\\resources\\route.json"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String data = new String(bytes);
        JSONArray jsonArray = (JSONArray) JSONArray.parse(data);
        for (Object json : jsonArray) {
            JSONObject jsonRoute = (JSONObject) json;
            ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
            String id = jsonRoute.getString("id");
            zuulRoute.setId(id);
            zuulRoute.setPath(jsonRoute.getString("path"));
            zuulRoute.setServiceId(jsonRoute.getString("serviceId"));

            String[] sensitiveHeaders = jsonRoute.getString("sensitiveHeaders").split(",");
            HashSet<String> stringHashSet = new HashSet<>();
            for(String header: sensitiveHeaders){
                stringHashSet.add(header);
            }
            zuulRoute.setSensitiveHeaders(stringHashSet);
            //zuulRoute.setUrl(jsonRoute.getString("url"));
            //zuulRoute.setLocation(jsonRoute.getString("location"));
            stringZuulRouteMap.put(zuulRoute.getPath(), zuulRoute);
        }

        return stringZuulRouteMap;
    }

    public static void main(String[] args) {
        byte[] bytes = new byte[0];
        try {
            bytes = Files.readAllBytes(Paths.get("D:\\Workspace\\service-zuul\\src\\main\\resources\\route.json"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String data = new String(bytes);
        System.out.println("data = " + data);
        JSONObject obj = (JSONObject) JSONObject.parse(data);
        System.out.println("obj = " + obj);

    }
}
